package vip.rpai.notepad
//添加、修改 记录
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast
import vip.rpai.notepad.databinding.ActivityAddInfoBinding
import java.util.*

class AddInfoActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddInfoBinding
    private val leSS = LeSS(this)
    private var position = -1//被调用传来的数值

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddInfoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }


    private fun initView() {
        binding.AddClearBT.setOnLongClickListener { addClearBTOnLongClick() }
        position = intent.extras?.getInt("position") ?: position
        binding.AddInfoET.text = null
        //如果传来的是下标就代表是要修改
        if (position >= 0) binding.AddInfoET.setText(LeSS.dataList[position].info)
    }

    private fun addClearBTOnLongClick(): Boolean {
        alert(getString(R.string.tipDeleteItemMessage), getString(R.string.tipDeleteItemTitle)) {
            positiveButton(getString(R.string.tipOK)) {
                leSS.reMoveData(arrayListOf(position))
                setResult(position)//回调
                finish()
            }
            negativeButton(getString(R.string.tipNO)) {}
        }.show()
        return true
    }

    fun addClearBTOnClick(v: View) {
        v.id
        if (binding.AddInfoET.text.isNullOrBlank()) {
            setResult(position)//回调
            finish()
        }
        binding.AddInfoET.text = null
    }

    fun addSaveITemBTOnClick(v: View) {
        v.id
        if (binding.AddInfoET.text.isNullOrBlank()) {
            toast(getString(R.string.addInfoETNullTip))
            return
        }

        if (position >= 0) {
            //修改列表里面的数据
            leSS.upDateData(position, binding.AddInfoET.text.toString(), Date().getNowDateTime())
            //修改数据库中的数据
        } else {
            val size = LeSS.dataList.size
            //有数据就递增，没数据id就是1
            val id = if ( size > 0) LeSS.dataList[size-1].id + 1 else 0
            leSS.addDataAndInsert(
                Fruit(id, binding.AddInfoET.text.toString(), Date().getNowDateTime())
            )
        }
        setResult(position)//回调
        finish()
    }
}